﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using UserInfo;
using Product;
using SqlOperate;
using System.Data.SqlClient;
using System.Text.RegularExpressions;
using Agent;
using Base;

namespace pub
{
    public partial class Form1 : Form
    {
         string tmp;
        DataTable dtType;
        public Form1()
        {
            InitializeComponent();
            dtType = GetIndustryType();
        }
        /// <summary>
        /// 得到行业类别
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        private DataTable  GetIndustryType()
        {
            IIndustryType it = new RIndustryType();
            DataTable dt= it.GetDataTable();
            dt.DefaultView.RowFilter = "SuperiorsFlag=0";
            return dt;
           
        }
        private string  GetTypeIDByName(string area,DataTable typedt)
        {
            
            foreach (DataRow dr in typedt.Rows) {
               if(dr["Type"].ToString().StartsWith(area )) return dr["ID"].ToString();
            }
            foreach (DataRow dr in typedt.Rows)
            {
                if (dr["Type"].ToString().StartsWith("四川")) return dr["ID"].ToString();
            }
           return "0";
        }
        #region 公司用户相关
        private void btnSaveCom_Click(object sender, EventArgs e)
        {
            int cntdone = 0;
            this.lblinfo.Text = "";
            com.Content objc;
            objc = new com.Content();
            objc.ConnectionString = this.txtCompany.Text;
            objc.Where.已采.Value = 0;
            objc.Where.已采.Operator = MyGeneration.dOOdads.WhereParameter.Operand.NotEqual;//已采
            objc.Where.已发.Value = 0;//未发
            objc.Query.Load();
            this.progressBar1.Maximum = objc.RowCount;
            this.progressBar1.Value = 0;
            while (!objc.EOF)
            {
                //下载并替换图片文件
                if (SaveUserInfo(objc)) { objc.已发 = true; cntdone += 1; }
                this.progressBar1.Value += 1;
                objc.MoveNext();

            };
            objc.Save();
            MessageBox.Show(string.Format("总共{0},成功{1}条！", objc.RowCount, cntdone));




        }
        private bool SaveUserInfo(com.Content obj)
        {
            string strError = "您提交的信息有以下错误，请重新提交!";
            IUserInfo RUser = new RUserInfo();
            TUserInfo TUser = new TUserInfo();            
            try
            {

                TUser.LoginName = obj.s_公司ID;
                TUser.Password = "scttcw";
                TUser.Email = "";
                TUser.Question = "您最喜欢的书是？";
                TUser.Answer = "scttcw";

                TUser.LinkName = obj.s_联系人;
                TUser.Sex = obj.s_性别;
                string[] dep = obj.s_职称.Split(' ');
                TUser.Department = (dep.GetLength(0) > 0) ? dep[0] : "";
                TUser.Position = (dep.GetLength(0) > 1) ? dep[1] : TUser.Department;
                string[] tel = obj.s_电话.Split(' ');
                TUser.Tel_International = "86";
                TUser.Tel_DistrictNumber = (tel.GetLength(0) > 0) ? tel[0] : "";
                TUser.Tel_Telephone = (tel.GetLength(0) > 1) ? tel[1] : TUser.Tel_DistrictNumber;
                TUser.Tel_Ext = "";
                string[] fax = obj.s_传真.Split(' ');
                TUser.Fax_International = "86";
                TUser.Fax_DistrictNumber = (fax.GetLength(0) > 0) ? fax[0] : ""; ;
                TUser.Fax_Telephone = (fax.GetLength(0) > 1) ? fax[1] : TUser.Fax_DistrictNumber;
                TUser.Fax_Ext = "";                
                TUser.MobilePhone = obj.s_手机;
                TUser.QQ = "";
                TUser.MSN = "";
                TUser.CompanyNature = obj.s_主营产品或服务;
                TUser.CompanyName = obj.s_标题;
                TUser.Summary = obj.s_公司介绍.Replace(" ","");

                TUser.DealinAdd = obj.s_地址;
                TUser.RegisterAddress=obj.s_注册地址;
                if(!string.IsNullOrEmpty(obj.s_注册资本.Trim())&&obj.s_注册资本.IndexOf('.')==0)
                    TUser.Capital=int.Parse(obj.s_注册资本.Trim());
                TUser.Corporate=obj.s_法人代表;
                if(!string.IsNullOrEmpty(obj.s_成立时间.Trim()))
                    TUser.Established=Convert.ToDateTime(obj.s_成立时间.Trim()+"-01"+"-01");


                TUser.Postalcode = obj.s_邮编;
                
                TUser.RegDate = Convert.ToDateTime(DateTime.Now.Date);
                string[] addr=obj.s_地址.Split(' ');
                TUser.Country = (addr.GetLength(0)>0)?addr[0]:"";
                TUser.Province = (addr.GetLength(0)>1)?addr[1]:"";
                TUser.City = (addr.GetLength(0)>2)?addr[2]:"";                
                TUser.Area = (addr.GetLength(0)>4)?addr[3]:"";
                TUser.Street = (addr.GetLength(0) > 4) ? addr[4] : ((addr.GetLength(0)>3)?addr[3]:"");
                
                TUser.Industry = (TUser.City=="")?this.GetTypeIDByName("四川",dtType):this.GetTypeIDByName(TUser.City.Substring(0,2),dtType);//行业代码
                TUser.GradeID = 1;
                TUser.Verify = false ;
                if (!string.IsNullOrEmpty(obj.Logo2))
                    TUser.Logo = Lion.Data.Library.HtmlEditor.Core.UpLoadHandler.DownloadPic(obj.Logo2, "jpg", txtImgPath.Text,false );
                else
                    TUser.Logo = "";
                TUser.URL = obj.s_公司网址;
                RUser.Insert(TUser);
                //再更新companty
            }
            catch (Exception ex)
            {
                lblinfo.Text  =  ex.Message ;
                return false ;
            }
            return true;

        }


        private void btnDelCom_Click(object sender, EventArgs e)
        {
            com.Content obj = new pub.com.Content();
            obj.ConnectionString = this.txtCompany.Text;
            obj.Where.已发.Value = false;
            obj.Query.Load();
            try
            {
                obj.DeleteAll();
                obj.Save();
                MessageBox.Show("删除成功，共删除" + obj.RowCount);

            }
            catch (Exception ex)
            {
                MessageBox.Show("删除失败，原因：" + ex.Message);
            }



        }
        #endregion

        #region 供应相关
        private void btnDelSup_Click(object sender, EventArgs e)
        {
            sup.Content obj = new sup.Content();
            obj.ConnectionString = this.txtSup.Text;
            obj.Where.已发.Value = false;
            obj.Query.Load();
            try
            {
                obj.DeleteAll();
                obj.Save();
                MessageBox.Show("删除成功，共删除" + obj.RowCount);

            }
            catch (Exception ex)
            {
                MessageBox.Show("删除失败，原因：" + ex.Message);
            }


        }
        private void btnSaveSup_Click(object sender, EventArgs e)
        {
            int cntdone = 0;
            this.lblinfo.Text = "";
            sup.Content objc;
            objc=new pub.sup.Content() ;
            objc.ConnectionString=this.txtSup.Text ;
            objc.Where.已采.Value = 0;
            objc.Where.已采.Operator = MyGeneration.dOOdads.WhereParameter.Operand.NotEqual;//已采
            objc.Where.已发.Value = 0;//未发
            objc.Query.Load();
            this.progressBar1.Maximum = objc.RowCount;
            this.progressBar1.Value = 0;
            while (!objc.EOF)
            {
                if (SaveSup(objc)) { objc.已发 = true; cntdone += 1; }
                this.progressBar1.Value += 1;
                objc.MoveNext();

            };
            objc.Save();
            MessageBox.Show(string.Format("总共{0},成功{1}条！",objc.RowCount,cntdone));

        }
        private bool SaveSup(sup.Content  obj)
        {
            try
            {
                int id = 0;
                RUserInfo User = new RUserInfo();
                DataTable  tableset = User.GetDataTable(string.Format(" where LoginName='{0}' ", obj.s_所属公司ID));
               id= int.Parse(tableset.Rows[0]["UserID"].ToString());
    

                TSupply TSup = new TSupply();
                TSup.UserID = id;
                TSup.Name = obj.s_标题 ;
                TSup.Key = obj.s_关键字 ;
                
                string[] pic=obj.s_图片1.Replace("|||","|").Split('|');
                if (pic.GetLength(0) > 0)
                    TSup.Picture_1 = Lion.Data.Library.HtmlEditor.Core.UpLoadHandler.DownloadPic((pic.GetLength(0) > 0) ? pic[0] : "", "jpg", this.txtImgPath.Text,true );
                else
                    TSup.Picture_1 = "";
                TSup.Thumbnail =TSup.Picture_1.Replace("m_","t_");//(pic.GetLength(0) > 0) ? pic[0] : "";        
                //if (dropProType.SelectedValue != "")
                //    TSup.ProType = int.Parse(dropProType.SelectedValue);
                //TSup.Place = this.txtPlace.Text;
                TSup.Brand =obj.s_品牌 ;
                TSup.Model = "" ;
                if (!string.IsNullOrEmpty(obj.s_价格.Trim()))
                    TSup.Price = Convert.ToDouble(obj.s_价格.Trim());
                else
                    TSup.Price = 0;
                TSup.Quantity = 9999;
                string[] units = obj.s_单位.Split('/');
                
               TSup.Units = (units.GetLength(0)>1)?units[1]:"";

                   // TSup.Minimum = 0;
                //TSup.Deadline = int.Parse(this.radlDeadline.SelectedValue);
               
                TSup.Info = obj.s_属性+obj.s_详情情况;
                //if (txtStartDate.Text != string.Empty)
                //    TSup.StartDate = Convert.ToDateTime(this.txtStartDate.Text);
                //else
                    TSup.StartDate = DateTime.Now;
                //if (txtEndDate.Text != string.Empty)
                //    TSup.EndDate = Convert.ToDateTime(this.txtEndDate.Text);
                //else
                    TSup.EndDate = DateTime.Now.AddYears(1);
                //TSup.Remark = this.txtRemark.Text;
                //TSup.Document = this.txtDocument.Text;
                ISupply RSup = new RSupply();
                //if (!Restr.Trim().Equals(string.Empty))
                //    Restr = Restr.Substring(0, Restr.Length - 1);
                int isEmail = 0;
                ////读取指定节点下的value值
                //string strFlag = Base.XMLProcess.Read("xml/EmailFlag.xml", "/Item/flag/mode[@type='supply']", "value");
                //if (strFlag == "")
                //    strFlag = "us_supply";
                //if (Restr.Trim().Equals(string.Empty)) //判断输入是否正确
                //{
                TSup.Place =obj.s_所在地;
                string[] citys = obj.s_所在地.Split(' ');

                TSup.IndType = (citys.GetLength(0) < 2) ? this.GetTypeIDByName("四川", dtType) : this.GetTypeIDByName(citys[1].Substring(0, 2), dtType); ;//行业类型
                TSup.Verify = 1;
                RSup.Insert(TSup, out isEmail);
                    //if (isEmail > 0)
                    //{
                    //    nspBase.Core.clsEmail.SendMail(strFlag, id);
                    //}
                    //ShowMessage("恭喜您，供应信息发布成功！", "Trade/SupplyManage.aspx?class=MenuLiCheck");

                //}
                //else
                //{
                //    lblMessage.Visible = true;
                //    lblMessage.Text = Restr + "填写有误！";
                //}
                    return true;
            }
            catch (Exception ex)
            {
                lblinfo.Text = ex.Message;
                return false;
               

            }
        }
        #endregion
        

        #region 采购相关

        /// <summary>
        /// 发布采购信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSavePur_Click(object sender, EventArgs e)
        {
            //得到IP

            using (System.Net.WebClient wc = new System.Net.WebClient()) { tmp = wc.DownloadString("http://www.ip138.com/ip2city.asp"); }
            tmp = tmp.Substring(tmp.IndexOf("[") + 1, tmp.IndexOf("]") - tmp.IndexOf("[") - 1);



            int cntdone = 0;
            this.lblinfo.Text = "";
            pur.Content objc;
            objc = new pur.Content();
            objc.ConnectionString = this.txtPur.Text;
            objc.Where.已采.Value = 0;
            objc.Where.已采.Operator = MyGeneration.dOOdads.WhereParameter.Operand.NotEqual;//已采
            objc.Where.已发.Value = 0;//未发
            objc.Query.Load();
            this.progressBar1.Maximum = objc.RowCount;
            this.progressBar1.Value = 0;
            while (!objc.EOF)
            {
                if (SavePurInfo(objc)) { objc.已发 = true; cntdone += 1; }
                this.progressBar1.Value += 1;
                objc.MoveNext();

            };
            objc.Save();
            MessageBox.Show(string.Format("总共{0},成功{1}条！", objc.RowCount, cntdone));

            

            
        }
        private bool SavePurInfo(pur.Content obj)
        {
            //string UserIP = Request.UserHostAddress;
            //string TelePhone = txtTel_International.Text.Trim() + txtTel_DistrictNumber.Text.Trim() + txtTel_Telephone.Text.Trim() + txtTel_Ext.Text.Trim();
            SqlConnection con = new SqlConnection(SqlHelper.ConnectionString);
            SqlCommand cmd = new SqlCommand("Pu_AddPurchase", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@LinkName", obj.LinkName );
            cmd.Parameters.AddWithValue("@CompanyName", obj.CompaneyName );
            cmd.Parameters.AddWithValue("@Email", "admin@mail.91fc.net");
            cmd.Parameters.AddWithValue("@TelePhone", "未留下");
            cmd.Parameters.AddWithValue("@Mobile", "未留下");
            cmd.Parameters.AddWithValue("@UserIP", tmp );
            SqlParameter ID = new SqlParameter("@ID", SqlDbType.Int);
            ID.Direction = ParameterDirection.Output;
            cmd.Parameters.Add(ID);
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
            //Response.Redirect("PurchaseAdd.aspx?VisitorID=" + ID.SqlValue.ToString() + "&Title=" + _KeyTitle);
            try
            {
                TPurchase TPur = new TPurchase();
                TPur.IsUser = "0";//非会员
                TPur.UserID = int.Parse(ID.SqlValue.ToString());
                TPur.IndType = obj.IndType ;
                    TPur.Name = obj.Name ;
                    TPur.Key = obj.Key ;
                TPur.Info = obj.Info ;
                TPur.Picture_1 = obj.Picture_1;
                TPur.StartDate = Convert.ToDateTime(obj.StartDate );
                TPur.EndDate = Convert.ToDateTime(obj.EndDate );
                TPur.Brand ="未指定";
                TPur.Model = "未指定";
                TPur.Unit = "未指定";
                TPur.Count = 0;
               // TPur.Price = "未指定";
                IPurchase Rpur = new RPurchase();
                    int isEmail = 0;
                    Rpur.Insert(TPur, out isEmail);
                    return true;

            }
            catch (Exception ex)
            {
                this.lblinfo.Text = ex.Message;
                return false;
            }
        }

        private void btnDelPur_Click(object sender, EventArgs e)
        {

        }
        #endregion
        #region 代理加盟信息
        private void btnSaveAge_Click(object sender, EventArgs e)
        {
            int cntdone = 0;
            this.lblinfo.Text = "";
            age.Content objc;
            objc = new age.Content();
            objc.ConnectionString = this.txtAge.Text;
            objc.Where.已采.Value = 0;
            objc.Where.已采.Operator = MyGeneration.dOOdads.WhereParameter.Operand.NotEqual;//已采
            objc.Where.已发.Value = 0;//未发
            objc.Query.Load();
            this.progressBar1.Maximum = objc.RowCount;
            this.progressBar1.Value = 0;
            while (!objc.EOF)
            {
                //下载并替换图片文件
                if (SaveAgeInfo(objc)) { objc.已发 = true; cntdone += 1; }
                this.progressBar1.Value += 1;
                objc.MoveNext();

            };
            objc.Save();
            MessageBox.Show(string.Format("总共{0},成功{1}条！", objc.RowCount, cntdone));




        }
        private bool SaveAgeInfo(age.Content obj)
        {
            try
            {
                int id = 0;
                RUserInfo User = new RUserInfo();
                DataTable tableset = User.GetDataTable(string.Format(" where LoginName='{0}' ", obj.s_所属公司ID));
                id = int.Parse(tableset.Rows[0]["UserID"].ToString());

                TSincereAgent TSin = new TSincereAgent();
                TSin.UserID = id;
                TSin.Name = obj.s_标题;
                TSin.Title = obj.s_标题;
                TSin.AgentType = 1;//第一个类别
                TSin.Validity = "六个月";
                TSin.Brand = obj.s_品牌;
                TSin.Investment = obj.s_基本投资额.Trim() +"万元";
                TSin.Amount = Convert.ToDecimal(obj.s_保证金额.Trim());
                TSin.InitialFee = Convert.ToDecimal(obj.s_加盟费.Trim());
                TSin.Require = obj.s_项目区域要求.Trim() ;
                if (obj.s_品牌发源地.Trim()  != "")
                    TSin.Cradle = obj.s_品牌发源地.Trim();
                if (obj.s_预计回报率.Trim() != "")
                    TSin.Payback = Convert.ToDecimal(obj.s_预计回报率.Trim());
                if (obj.s_预计回报周期.Trim() != "")
                    TSin.Period = Convert.ToDecimal(obj.s_预计回报周期.Trim());
                if (obj.s_特许权使用费.Trim()  != "")
                    TSin.Concession = Convert.ToDecimal(obj.s_特许权使用费.Trim());
                if (obj.s_合同期限.Trim() != "")
                    TSin.Contract = Convert.ToDecimal(obj.s_合同期限.Trim());
                //if (radlisMoreBrand.SelectedValue != "")
                   // TSin.isMoreBrand = Convert.ToBoolean(radlisMoreBrand.SelectedValue);

                if (Common.CheckNum(obj.s_加盟商总数.Trim()))
                {
                    TSin.Count = Convert.ToInt32(obj.s_加盟商总数.Trim());
                }
                if (Common.CheckNum(obj.s_特许经营时间.Trim()))
                {
                    TSin.BusinessDate = Convert.ToInt32(obj.s_特许经营时间.Trim());
                }
               
                TSin.BusinessMode = obj.s_经营模式;
               
                TSin.Developmental = obj.s_发展模式;
                TSin.Detail = obj.s_详情情况;
           
                string[] pic = obj.s_图片1.Replace("|||", "|").Split('|');
                if (pic.GetLength(0) > 0)
                    TSin.Picture = Lion.Data.Library.HtmlEditor.Core.UpLoadHandler.DownloadPic((pic.GetLength(0) > 0) ? pic[0] : "", "jpg", this.txtImgPath.Text, true);
                else
                    TSin.Picture = "";
                ISincereAgent RSin = new RSincereAgent();
                int isEmail = 0;
                RSin.Insert(TSin, out isEmail);
                return true;
                
            }
            catch (Exception ex)
            {
                lblinfo.Text = ex.Message;
                return false;
            }

        
        }
        #endregion
    }
}